package com.madzone.gae.filem.model;

import java.util.List;

import javax.jdo.PersistenceManager;
import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;

import com.google.appengine.api.datastore.Blob;
import com.madzone.wiki.gae.ds.model.PMF;

@PersistenceCapable
public class BinaryFile extends File<Blob> {
	
	@Persistent
	private Blob content;
	
	public BinaryFile(String fileName, byte[] content) {
		super(fileName);
		setContentBytes(content);
	}
	
	public BinaryFile() {
	}
	
	public Blob getContent() {
		return content;
	}

	public void setContent(Blob content) {
		this.content = content;
	}

	@Override
	public byte[] getContentBytes() {
		Blob content = getContent();
		if (content != null) {
			return content.getBytes();
		}
		return null;
	}

	@Override
	public void setContentBytes(byte[] contentBytes) {
		if (contentBytes == null) return;
		Blob content = new Blob(contentBytes);
		setContent(content);
	}
	
	public static File getByName(String fileName) {
		String query = "select from " + BinaryFile.class.getName() + " where fileName == '" + fileName +"'";
		PersistenceManager pm = PMF.getPM();
		try {
			List<File> files = (List<File>) pm.newQuery(query).execute();
			if (files.isEmpty()) {
				return null;
			}
			return files.get(0);
		} finally {
			//pm.close();
		}
	}

}
